import { RedisInstance } from './redis';

class LadderAlgorithm{
    constructor(){

    }
    redis = undefined
    redisKey = 'ladderalgorithm:'

    levelList = {
        1: { type:'ad', max:2, ss: 15, adUnitId: 'adunit-47b5c7839283c0d0' }, 
        2: { type:'ad', max:2, ss: 30, adUnitId: 'adunit-eccfdd27304bfb5a' }, 
        3: { type:'ad', max:2, ss: 60, adUnitId: 'adunit-efbb83ce136be769' }, 
        4: { type:'consume', max: 9999999999 }
    }

    levelListProd = {
        1: { type:'ad', max:2, ss: 15, adUnitId: 'adunit-2189206b8cdaee1f' }, 
        2: { type:'ad', max:2, ss: 30, adUnitId: 'adunit-d798cc74d79efa56' }, 
        3: { type:'ad', max:2, ss: 60, adUnitId: 'adunit-2b1fa290fe1bc503' }, 
        4: { type:'consume', max: 9999999999 }
    }

    async getRedis(){
        if(!this.redis){
            const redis = RedisInstance.initRedis();
            this.redis = redis
        }
        return this.redis
    }
    
    get(wx_user: string){
        return new Promise(async (resolve, reject) => {
            const redis:any = await this.getRedis()
            let level = 1
            let key = this.redisKey + wx_user + ':'
            let loop = async (cb) => {
                let currentLevel = process.env.ServerApp === 'prod' ? this.levelListProd[level] : this.levelList[level]
                let findAccessKey = await redis.get(key + level)
                if(findAccessKey){
                    if(findAccessKey >= currentLevel.max){
                        level++
                        loop(cb)
                    }else{
                        cb(currentLevel, Number(findAccessKey) + 1)
                    }
                }else{
                    cb(currentLevel, 1)
                }
            }

            loop(async (currentLevel, count) => {
                resolve({
                    type: currentLevel.type,
                    ss: currentLevel.ss,
                    adUnitId: currentLevel.adUnitId,
                    count: count,
                    level: level
                })
            })
        })
    }
    async set(wx_user){
        const redis:any = await this.getRedis()
        let currentLevel:any = await this.get(wx_user)
        let key = this.redisKey + wx_user + ':' + currentLevel.level
        await redis.set(key, currentLevel.count)
        let nowTime = new Date().getTime()
        let outTime = new Date()
        outTime.setHours(23)
        outTime.setMinutes(59)
        outTime.setMilliseconds(59)
        let timeout = parseInt(((outTime.getTime() - nowTime) / 1000).toString())
        await redis.expire(key, timeout)
    }
}
export default new LadderAlgorithm()